use aes_gcm::aead::Aead;
use aes_gcm::{Aes256Gcm, Key, KeyInit, Nonce};
use base64::{Engine as _, engine::general_purpose};
use hmac::{Hmac, Mac};
use rand::{Rng, thread_rng};
use regex::Regex;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::time::{SystemTime, UNIX_EPOCH};
use thiserror::Error;
use url::Url;

// ================== 错误定义 ==================

#[derive(Error, Debug, Clone, Serialize, Deserialize)]
pub enum SecurityError {
    #[error("路径越权攻击检测: {detail}")]
    PathTraversal { detail: String },

    #[error("XSS脚本注入检测: {detail}")]
    XssInjection { detail: String },

    #[error("SQL注入攻击检测: {detail}")]
    SqlInjection { detail: String },

    #[error("CSRF攻击检测: {detail}")]
    CsrfAttack { detail: String },

    #[error("请求头异常: {detail}")]
    InvalidHeader { detail: String },

    #[error("文件上传安全检查失败: {detail}")]
    FileUploadSecurity { detail: String },

    #[error("频率限制触发: {detail}")]
    RateLimit { detail: String },

    #[error("加密操作失败: {detail}")]
    CryptoError { detail: String },
}

// ================== 检查结果 ==================

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityCheckResult {
    pub is_safe: bool,
    pub violations: Vec<SecurityViolation>,
    pub check_time: u64,
    pub request_id: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityViolation {
    pub rule_type: SecurityRuleType,
    pub severity: SecuritySeverity,
    pub message: String,
    pub field: Option<String>,
    pub value: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SecurityRuleType {
    PathTraversal,
    XssInjection,
    SqlInjection,
    CsrfProtection,
    InvalidHeader,
    FileUploadSecurity,
    RateLimit,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SecuritySeverity {
    Low,
    Medium,
    High,
    Critical,
}

// ================== HTTP 请求信息 ==================

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HttpRequestInfo {
    pub method: String,
    pub url: String,
    pub headers: HashMap<String, String>,
    pub body: Option<String>,
    pub query_params: HashMap<String, String>,
    pub form_data: HashMap<String, String>,
    pub cookies: HashMap<String, String>,
    pub client_ip: String,
    pub user_agent: Option<String>,
    pub referer: Option<String>,
}

// ================== 安全配置 ==================

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityConfig {
    pub enable_path_traversal_check: bool,
    pub enable_xss_check: bool,
    pub enable_sql_injection_check: bool,
    pub enable_csrf_check: bool,
    pub enable_rate_limit: bool,
    pub allowed_file_extensions: Vec<String>,
    pub max_request_size: usize,
    pub csrf_token_name: String,
    pub rate_limit_requests: u32,
    pub rate_limit_window_seconds: u64,
}

impl Default for SecurityConfig {
    fn default() -> Self {
        SecurityConfig {
            enable_path_traversal_check: true,
            enable_xss_check: true,
            enable_sql_injection_check: true,
            enable_csrf_check: true,
            enable_rate_limit: true,
            allowed_file_extensions: vec![
                "jpg".to_string(),
                "jpeg".to_string(),
                "png".to_string(),
                "gif".to_string(),
                "pdf".to_string(),
                "txt".to_string(),
            ],
            max_request_size: 10_000_000, // 10MB
            csrf_token_name: "csrf_token".to_string(),
            rate_limit_requests: 100,
            rate_limit_window_seconds: 3600,
        }
    }
}

// ================== 主要安全检查器 ==================

pub struct SecurityGuard {
    config: SecurityConfig,
    rate_limit_store: HashMap<String, Vec<u64>>,
    csrf_tokens: HashMap<String, u64>,
}

impl SecurityGuard {
    pub fn new(config: SecurityConfig) -> Self {
        SecurityGuard {
            config,
            rate_limit_store: HashMap::new(),
            csrf_tokens: HashMap::new(),
        }
    }

    pub fn new_with_default() -> Self {
        SecurityGuard::new(SecurityConfig::default())
    }

    /// 主要的安全检查入口
    pub fn check_request(&mut self, request: &HttpRequestInfo) -> SecurityCheckResult {
        let request_id = uuid::Uuid::new_v4().to_string();
        let check_time = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let mut violations = Vec::new();

        // 路径越权检查
        if self.config.enable_path_traversal_check {
            if let Some(violation) = self.check_path_traversal(request) {
                violations.push(violation);
            }
        }

        // XSS检查
        if self.config.enable_xss_check {
            violations.extend(self.check_xss_injection(request));
        }

        // SQL注入检查
        if self.config.enable_sql_injection_check {
            violations.extend(self.check_sql_injection(request));
        }

        // CSRF检查
        if self.config.enable_csrf_check {
            if let Some(violation) = self.check_csrf_protection(request) {
                violations.push(violation);
            }
        }

        // 频率限制检查
        if self.config.enable_rate_limit {
            if let Some(violation) = self.check_rate_limit(request) {
                violations.push(violation);
            }
        }

        // 请求头检查
        violations.extend(self.check_headers(request));

        // 文件上传安全检查
        violations.extend(self.check_file_upload_security(request));

        SecurityCheckResult {
            is_safe: violations.is_empty(),
            violations,
            check_time,
            request_id,
        }
    }

    /// 路径越权检查
    fn check_path_traversal(&self, request: &HttpRequestInfo) -> Option<SecurityViolation> {
        let path_patterns = vec![
            // 基本路径遍历
            r"\.\.[\\/]",
            r"[\\/]\.\.[\\/]",
            r"\.\.%2f",
            r"%2e%2e%2f",
            r"%2e%2e/",
            r"\.\.%5c",
            r"%2e%2e%5c",
            // URL编码变种
            r"%2e%2e%2f",
            r"%2e%2e%5c",
            r"%252e%252e%252f",
            r"%252e%252e%255c",
            // 双重编码
            r"%c0%ae%c0%ae%c0%af",
            r"%c0%ae%c0%ae%c0%5c",
            // Unicode编码
            r"%u002e%u002e%u002f",
            r"%u002e%u002e%u005c",
            // 其他变种
            r"\.\.%252f",
            r"\.\.%255c",
            r"\.\.%c0%af",
            r"\.\.%c1%9c",
            // 空字节注入
            r"\.\.%00",
            r"%00\.\.",
            // 长路径攻击
            r"\.\./\.\./\.\./\.\./\.\./",
            r"\.\.\\\.\.\\\.\.\\\.\.\\\.\.\\",
        ];

        let full_text = format!(
            "{} {} {}",
            request.url,
            request
                .query_params
                .values()
                .cloned()
                .collect::<Vec<_>>()
                .join(" "),
            request
                .form_data
                .values()
                .cloned()
                .collect::<Vec<_>>()
                .join(" ")
        );

        for pattern in path_patterns {
            if let Ok(regex) = Regex::new(&format!("(?i){}", pattern)) {
                if regex.is_match(&full_text) {
                    return Some(SecurityViolation {
                        rule_type: SecurityRuleType::PathTraversal,
                        severity: SecuritySeverity::High,
                        message: format!("检测到路径越权攻击模式: {}", pattern),
                        field: Some("url/params".to_string()),
                        value: Some(full_text),
                    });
                }
            }
        }

        // 检查特殊文件名
        let dangerous_files = vec![
            "passwd",
            "shadow",
            "hosts",
            "services",
            "protocols",
            "sam",
            "system",
            "config",
            "boot.ini",
            "win.ini",
            "web.config",
            "app.config",
            ".env",
            ".htaccess",
            "wp-config.php",
            "config.php",
            "database.yml",
        ];

        for file in dangerous_files {
            if full_text.to_lowercase().contains(file) {
                return Some(SecurityViolation {
                    rule_type: SecurityRuleType::PathTraversal,
                    severity: SecuritySeverity::High,
                    message: format!("检测到访问敏感文件: {}", file),
                    field: Some("url/params".to_string()),
                    value: Some(full_text),
                });
            }
        }

        None
    }

    /// XSS脚本注入检查
    fn check_xss_injection(&self, request: &HttpRequestInfo) -> Vec<SecurityViolation> {
        let mut violations = Vec::new();

        let xss_patterns = vec![
            // 基本脚本标签
            r"<script[^>]*>.*?</script>",
            r"<script[^>]*>",
            r"</script>",
            // JavaScript协议
            r"javascript:",
            r"vbscript:",
            r"data:text/html",
            r"data:application/javascript",
            // 事件处理器
            r"on\w+\s*=",
            r"onload\s*=",
            r"onerror\s*=",
            r"onclick\s*=",
            r"onmouseover\s*=",
            r"onfocus\s*=",
            r"onblur\s*=",
            r"onchange\s*=",
            r"onsubmit\s*=",
            r"onreset\s*=",
            r"onselect\s*=",
            r"onkeydown\s*=",
            r"onkeyup\s*=",
            r"onkeypress\s*=",
            // 危险标签
            r"<iframe[^>]*>",
            r"<object[^>]*>",
            r"<embed[^>]*>",
            r"<applet[^>]*>",
            r"<form[^>]*>",
            r"<input[^>]*>",
            r"<textarea[^>]*>",
            r"<select[^>]*>",
            r"<option[^>]*>",
            r"<link[^>]*>",
            r"<meta[^>]*>",
            r"<style[^>]*>",
            // 特殊属性
            r"<img[^>]*onerror[^>]*>",
            r"<svg[^>]*onload[^>]*>",
            r"<body[^>]*onload[^>]*>",
            r"<div[^>]*onclick[^>]*>",
            "<a[^>]*href\\s*=\\s*[\"']?javascript:",
            "<a[^>]*href\\s*=\\s*[\"']?vbscript:",
            // JavaScript函数
            r"eval\s*\(",
            r"alert\s*\(",
            r"confirm\s*\(",
            r"prompt\s*\(",
            r"document\.write\s*\(",
            r"document\.writeln\s*\(",
            r"innerHTML\s*=",
            r"outerHTML\s*=",
            r"insertAdjacentHTML\s*\(",
            r"setTimeout\s*\(",
            r"setInterval\s*\(",
            r"Function\s*\(",
            r"setAttribute\s*\(",
            // 编码绕过
            r"&#x3c;script",
            r"&#60;script",
            r"%3cscript",
            r"%3Cscript",
            r"&lt;script",
            r"&LT;script",
            // CSS注入
            r"expression\s*\(",
            r"@import",
            r"url\s*\(",
            r"behavior\s*:",
            // 其他危险模式
            r"document\.cookie",
            r"window\.location",
            r"location\.href",
            r"location\.replace",
            r"location\.assign",
            r"history\.back",
            r"history\.forward",
            r"history\.go",
            r"XMLHttpRequest",
            r"fetch\s*\(",
            r"WebSocket\s*\(",
        ];

        // 检查所有可能包含用户输入的字段
        let fields_to_check = vec![
            (
                "query_params".to_string(),
                request
                    .query_params
                    .values()
                    .cloned()
                    .collect::<Vec<_>>()
                    .join(" "),
            ),
            (
                "form_data".to_string(),
                request
                    .form_data
                    .values()
                    .cloned()
                    .collect::<Vec<_>>()
                    .join(" "),
            ),
            ("body".to_string(), request.body.clone().unwrap_or_default()),
        ];

        for (field_name, content) in fields_to_check {
            for pattern in &xss_patterns {
                if let Ok(regex) = Regex::new(&format!("(?i){}", pattern)) {
                    if regex.is_match(&content) {
                        violations.push(SecurityViolation {
                            rule_type: SecurityRuleType::XssInjection,
                            severity: SecuritySeverity::High,
                            message: format!("检测到XSS攻击模式: {}", pattern),
                            field: Some(field_name.clone()),
                            value: Some(content.clone()),
                        });
                    }
                }
            }
        }

        violations
    }

    /// SQL注入检查
    fn check_sql_injection(&self, request: &HttpRequestInfo) -> Vec<SecurityViolation> {
        let mut violations = Vec::new();

        let sql_patterns = vec![
            // 基本SQL关键字
            r"\b(union|select|insert|update|delete|drop|create|alter|exec|execute)\b",
            r"\b(union\s+all|union\s+select)\b",
            r"\b(select\s+.*\s+from)\b",
            r"\b(insert\s+into)\b",
            r"\b(update\s+.*\s+set)\b",
            r"\b(delete\s+from)\b",
            r"\b(drop\s+table|drop\s+database)\b",
            r"\b(create\s+table|create\s+database)\b",
            r"\b(alter\s+table)\b",
            // 注释符
            r"';.*--",
            r"'.*--",
            r"'.*#",
            r"'.*/\*.*\*/",
            r"'.*/\*",
            r"\*/.*'",
            // 逻辑操作符
            r"'.*or.*'.*'",
            r"'.*and.*'.*'",
            r"'.*or\s+1\s*=\s*1.*'",
            r"'.*and\s+1\s*=\s*1.*'",
            r"'.*or\s+true.*'",
            r"'.*and\s+true.*'",
            r"'.*or\s+false.*'",
            r"'.*and\s+false.*'",
            // 通配符和函数
            r"\*.*from.*where",
            r"'.*like.*'",
            r"'.*in\s*\(.*'",
            r"'.*between.*'",
            r"'.*exists\s*\(.*'",
            r"'.*count\s*\(.*'",
            r"'.*sum\s*\(.*'",
            r"'.*avg\s*\(.*'",
            r"'.*max\s*\(.*'",
            r"'.*min\s*\(.*'",
            // 时间延迟攻击
            r"';.*waitfor.*delay.*'",
            r"'.*sleep\s*\(.*'",
            r"'.*benchmark\s*\(.*'",
            r"'.*pg_sleep\s*\(.*'",
            // 系统函数
            r"'.*xp_cmdshell.*'",
            r"'.*sp_.*'",
            r"'.*master\.dbo\..*'",
            r"'.*sys\.databases.*'",
            r"'.*sys\.tables.*'",
            r"'.*sys\.columns.*'",
            r"'.*sys\.users.*'",
            // 字符串连接
            r"\|\|\s*'",
            r"'.*\|\|.*'",
            r"'.*concat\s*\(.*'",
            r"'.*char\s*\(.*'",
            r"'.*ascii\s*\(.*'",
            // 系统信息
            r"@@version",
            r"@@servername",
            r"@@hostname",
            r"@@datadir",
            r"@@basedir",
            r"version\s*\(\s*\)",
            r"user\s*\(\s*\)",
            r"database\s*\(\s*\)",
            r"current_user",
            r"current_database",
            // 系统表
            r"information_schema",
            r"sysobjects",
            r"syscolumns",
            r"sysdatabases",
            r"sysusers",
            r"mysql\.user",
            r"mysql\.db",
            r"pg_user",
            r"pg_database",
            r"pg_tables",
            r"pg_columns",
            // 文件操作
            r"'.*load_file\s*\(.*'",
            r"'.*into\s+outfile.*'",
            r"'.*into\s+dumpfile.*'",
            r"'.*copy\s+.*'",
            // 编码绕过
            r"'.*char\s*\(.*0x.*'",
            r"'.*0x[0-9a-fA-F]+.*'",
            r"'.*unhex\s*\(.*'",
            r"'.*hex\s*\(.*'",
            // 其他危险模式
            r"'.*having\s+.*'",
            r"'.*group\s+by.*'",
            r"'.*order\s+by.*'",
            r"'.*limit\s+.*'",
            r"'.*offset\s+.*'",
            r"'.*case\s+when.*'",
            r"'.*if\s*\(.*'",
            r"'.*cast\s*\(.*'",
            r"'.*convert\s*\(.*'",
        ];

        let fields_to_check = vec![
            (
                "query_params".to_string(),
                request
                    .query_params
                    .values()
                    .cloned()
                    .collect::<Vec<_>>()
                    .join(" "),
            ),
            (
                "form_data".to_string(),
                request
                    .form_data
                    .values()
                    .cloned()
                    .collect::<Vec<_>>()
                    .join(" "),
            ),
            ("body".to_string(), request.body.clone().unwrap_or_default()),
        ];

        for (field_name, content) in fields_to_check {
            for pattern in &sql_patterns {
                if let Ok(regex) = Regex::new(&format!("(?i){}", pattern)) {
                    if regex.is_match(&content) {
                        violations.push(SecurityViolation {
                            rule_type: SecurityRuleType::SqlInjection,
                            severity: SecuritySeverity::Critical,
                            message: format!("检测到SQL注入攻击模式: {}", pattern),
                            field: Some(field_name.clone()),
                            value: Some(content.clone()),
                        });
                    }
                }
            }
        }

        violations
    }

    /// 文件上传安全检查
    fn check_file_upload_security(&self, request: &HttpRequestInfo) -> Vec<SecurityViolation> {
        let mut violations = Vec::new();

        // 检查Content-Type是否为文件上传
        if let Some(content_type) = request.headers.get("content-type") {
            if content_type.contains("multipart/form-data") {
                // 检查文件扩展名
                let dangerous_extensions = vec![
                    "exe", "bat", "cmd", "com", "pif", "scr", "vbs", "js", "jar", "php", "asp",
                    "aspx", "jsp", "py", "pl", "sh", "cgi", "rb", "ps1", "psm1", "psd1", "ps1xml",
                    "psc1", "pssc", "cdxml", "msh", "msh1", "msh2", "mshxml", "msh1xml", "msh2xml",
                    "scf", "lnk", "inf", "reg", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf",
                    "rtf", "zip", "rar", "7z", "tar", "gz",
                ];

                // 检查请求体中的文件名
                if let Some(body) = &request.body {
                    for ext in &dangerous_extensions {
                        if body.to_lowercase().contains(&format!(".{}", ext)) {
                            violations.push(SecurityViolation {
                                rule_type: SecurityRuleType::FileUploadSecurity,
                                severity: SecuritySeverity::High,
                                message: format!("检测到危险文件扩展名: .{}", ext),
                                field: Some("file_extension".to_string()),
                                value: Some(format!(".{}", ext)),
                            });
                        }
                    }

                    // 检查文件头魔数
                    let dangerous_magic_numbers = vec![
                        ("MZ", "可执行文件"),
                        ("PK", "压缩文件"),
                        ("%PDF", "PDF文件"),
                        ("<?php", "PHP脚本"),
                        ("<%@", "ASP脚本"),
                        ("#!/", "Shell脚本"),
                        ("<script", "JavaScript文件"),
                    ];

                    for (magic, description) in &dangerous_magic_numbers {
                        if body.contains(magic) {
                            violations.push(SecurityViolation {
                                rule_type: SecurityRuleType::FileUploadSecurity,
                                severity: SecuritySeverity::High,
                                message: format!("检测到危险文件类型: {}", description),
                                field: Some("file_content".to_string()),
                                value: Some(magic.to_string()),
                            });
                        }
                    }
                }

                // 检查表单数据中的文件名
                for (key, value) in &request.form_data {
                    if key.to_lowercase().contains("filename")
                        || key.to_lowercase().contains("file")
                    {
                        for ext in &dangerous_extensions {
                            if value.to_lowercase().contains(&format!(".{}", ext)) {
                                violations.push(SecurityViolation {
                                    rule_type: SecurityRuleType::FileUploadSecurity,
                                    severity: SecuritySeverity::High,
                                    message: format!("检测到危险文件扩展名: .{}", ext),
                                    field: Some(key.clone()),
                                    value: Some(value.clone()),
                                });
                            }
                        }
                    }
                }
            }
        }

        // 检查文件大小
        if let Some(content_length) = request.headers.get("content-length") {
            if let Ok(size) = content_length.parse::<usize>() {
                if size > self.config.max_request_size {
                    violations.push(SecurityViolation {
                        rule_type: SecurityRuleType::FileUploadSecurity,
                        severity: SecuritySeverity::Medium,
                        message: format!("文件大小超过限制: {} bytes", size),
                        field: Some("content-length".to_string()),
                        value: Some(content_length.clone()),
                    });
                }
            }
        }

        violations
    }

    /// CSRF保护检查
    fn check_csrf_protection(&self, request: &HttpRequestInfo) -> Option<SecurityViolation> {
        // 对于GET请求通常不需要CSRF检查
        if request.method.to_uppercase() == "GET" {
            return None;
        }

        // 检查是否存在CSRF token
        let token = request
            .form_data
            .get(&self.config.csrf_token_name)
            .or_else(|| request.headers.get(&self.config.csrf_token_name))
            .or_else(|| request.headers.get("x-csrf-token"));

        if token.is_none() {
            return Some(SecurityViolation {
                rule_type: SecurityRuleType::CsrfProtection,
                severity: SecuritySeverity::High,
                message: "缺少CSRF保护token".to_string(),
                field: Some("csrf_token".to_string()),
                value: None,
            });
        }

        // 检查Referer头
        if let Some(referer) = &request.referer {
            if let (Ok(referer_url), Ok(request_url)) =
                (Url::parse(referer), Url::parse(&request.url))
            {
                if referer_url.host() != request_url.host() {
                    return Some(SecurityViolation {
                        rule_type: SecurityRuleType::CsrfProtection,
                        severity: SecuritySeverity::Medium,
                        message: "Referer域名与请求域名不匹配".to_string(),
                        field: Some("referer".to_string()),
                        value: Some(referer.clone()),
                    });
                }
            }
        }

        None
    }

    /// 频率限制检查
    fn check_rate_limit(&mut self, request: &HttpRequestInfo) -> Option<SecurityViolation> {
        let current_time = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let requests = self
            .rate_limit_store
            .entry(request.client_ip.clone())
            .or_insert_with(Vec::new);

        // 清理过期记录
        requests.retain(|&time| current_time - time < self.config.rate_limit_window_seconds);

        // 检查是否超过限制
        if requests.len() >= self.config.rate_limit_requests as usize {
            return Some(SecurityViolation {
                rule_type: SecurityRuleType::RateLimit,
                severity: SecuritySeverity::Medium,
                message: format!("IP {} 请求频率超过限制", request.client_ip),
                field: Some("client_ip".to_string()),
                value: Some(request.client_ip.clone()),
            });
        }

        // 记录当前请求
        requests.push(current_time);
        None
    }

    /// 请求头检查
    fn check_headers(&self, request: &HttpRequestInfo) -> Vec<SecurityViolation> {
        let mut violations = Vec::new();

        // 检查User-Agent
        if let Some(ua) = &request.user_agent {
            if ua.is_empty() || ua.len() < 10 {
                violations.push(SecurityViolation {
                    rule_type: SecurityRuleType::InvalidHeader,
                    severity: SecuritySeverity::Low,
                    message: "可疑的User-Agent头".to_string(),
                    field: Some("user-agent".to_string()),
                    value: Some(ua.clone()),
                });
            }

            // 检查恶意User-Agent
            let malicious_ua_patterns = vec![
                r"sqlmap",
                r"nikto",
                r"nmap",
                r"masscan",
                r"zap",
                r"burp",
                r"w3af",
                r"havij",
                r"pangolin",
                r"acunetix",
                r"nessus",
                r"openvas",
                r"wget",
                r"curl",
                r"python-requests",
                r"libwww-perl",
                r"lwp-trivial",
            ];

            for pattern in malicious_ua_patterns {
                if let Ok(regex) = Regex::new(&format!("(?i){}", pattern)) {
                    if regex.is_match(ua) {
                        violations.push(SecurityViolation {
                            rule_type: SecurityRuleType::InvalidHeader,
                            severity: SecuritySeverity::High,
                            message: format!("检测到恶意User-Agent: {}", pattern),
                            field: Some("user-agent".to_string()),
                            value: Some(ua.clone()),
                        });
                    }
                }
            }
        }

        // 检查Content-Type
        if let Some(content_type) = request.headers.get("content-type") {
            if content_type.contains("multipart/form-data") && !content_type.contains("boundary=") {
                violations.push(SecurityViolation {
                    rule_type: SecurityRuleType::InvalidHeader,
                    severity: SecuritySeverity::Medium,
                    message: "multipart/form-data缺少boundary".to_string(),
                    field: Some("content-type".to_string()),
                    value: Some(content_type.clone()),
                });
            }

            // 检查恶意Content-Type
            let malicious_content_types = vec![
                "application/x-php",
                "text/x-php",
                "application/x-httpd-php",
                "application/x-httpd-php-source",
                "application/x-javascript",
                "text/javascript",
                "application/x-sh",
                "text/x-sh",
                "application/x-executable",
            ];

            for malicious_type in malicious_content_types {
                if content_type.to_lowercase().contains(malicious_type) {
                    violations.push(SecurityViolation {
                        rule_type: SecurityRuleType::InvalidHeader,
                        severity: SecuritySeverity::High,
                        message: format!("检测到恶意Content-Type: {}", malicious_type),
                        field: Some("content-type".to_string()),
                        value: Some(content_type.clone()),
                    });
                }
            }
        }

        // 检查Host头
        if let Some(host) = request.headers.get("host") {
            // 检查Host头注入
            if host.contains("\r") || host.contains("\n") || host.contains("\0") {
                violations.push(SecurityViolation {
                    rule_type: SecurityRuleType::InvalidHeader,
                    severity: SecuritySeverity::High,
                    message: "检测到Host头注入攻击".to_string(),
                    field: Some("host".to_string()),
                    value: Some(host.clone()),
                });
            }

            // 检查IP地址
            if host.parse::<std::net::IpAddr>().is_ok() {
                violations.push(SecurityViolation {
                    rule_type: SecurityRuleType::InvalidHeader,
                    severity: SecuritySeverity::Medium,
                    message: "Host头使用IP地址而非域名".to_string(),
                    field: Some("host".to_string()),
                    value: Some(host.clone()),
                });
            }
        }

        // 检查Referer头
        if let Some(referer) = &request.referer {
            // 检查Referer头注入
            if referer.contains("\r") || referer.contains("\n") || referer.contains("\0") {
                violations.push(SecurityViolation {
                    rule_type: SecurityRuleType::InvalidHeader,
                    severity: SecuritySeverity::High,
                    message: "检测到Referer头注入攻击".to_string(),
                    field: Some("referer".to_string()),
                    value: Some(referer.clone()),
                });
            }
        }

        // 检查Accept头
        if let Some(accept) = request.headers.get("accept") {
            // 检查Accept头注入
            if accept.contains("\r") || accept.contains("\n") || accept.contains("\0") {
                violations.push(SecurityViolation {
                    rule_type: SecurityRuleType::InvalidHeader,
                    severity: SecuritySeverity::High,
                    message: "检测到Accept头注入攻击".to_string(),
                    field: Some("accept".to_string()),
                    value: Some(accept.clone()),
                });
            }
        }

        // 检查Authorization头
        if let Some(auth) = request.headers.get("authorization") {
            // 检查Authorization头注入
            if auth.contains("\r") || auth.contains("\n") || auth.contains("\0") {
                violations.push(SecurityViolation {
                    rule_type: SecurityRuleType::InvalidHeader,
                    severity: SecuritySeverity::High,
                    message: "检测到Authorization头注入攻击".to_string(),
                    field: Some("authorization".to_string()),
                    value: Some(auth.clone()),
                });
            }
        }

        // 检查Cookie头
        if let Some(cookie) = request.headers.get("cookie") {
            // 检查Cookie头注入
            if cookie.contains("\r") || cookie.contains("\n") || cookie.contains("\0") {
                violations.push(SecurityViolation {
                    rule_type: SecurityRuleType::InvalidHeader,
                    severity: SecuritySeverity::High,
                    message: "检测到Cookie头注入攻击".to_string(),
                    field: Some("cookie".to_string()),
                    value: Some(cookie.clone()),
                });
            }
        }

        // 检查X-Forwarded-For头
        if let Some(xff) = request.headers.get("x-forwarded-for") {
            // 检查X-Forwarded-For头注入
            if xff.contains("\r") || xff.contains("\n") || xff.contains("\0") {
                violations.push(SecurityViolation {
                    rule_type: SecurityRuleType::InvalidHeader,
                    severity: SecuritySeverity::High,
                    message: "检测到X-Forwarded-For头注入攻击".to_string(),
                    field: Some("x-forwarded-for".to_string()),
                    value: Some(xff.clone()),
                });
            }
        }

        // 检查Content-Length头
        if let Some(content_length) = request.headers.get("content-length") {
            if let Ok(length) = content_length.parse::<usize>() {
                if length == 0
                    && request.method.to_uppercase() != "GET"
                    && request.method.to_uppercase() != "HEAD"
                {
                    violations.push(SecurityViolation {
                        rule_type: SecurityRuleType::InvalidHeader,
                        severity: SecuritySeverity::Low,
                        message: "非GET/HEAD请求的Content-Length为0".to_string(),
                        field: Some("content-length".to_string()),
                        value: Some(content_length.clone()),
                    });
                }
            }
        }

        violations
    }

    /// 输入验证和过滤
    pub fn validate_and_filter_input(
        &self,
        input: &str,
        input_type: InputType,
    ) -> Result<String, SecurityError> {
        match input_type {
            InputType::Email => self.validate_email(input),
            InputType::Url => self.validate_url(input),
            InputType::Phone => self.validate_phone(input),
            InputType::Username => self.validate_username(input),
            InputType::Password => self.validate_password(input),
            InputType::Numeric => self.validate_numeric(input),
            InputType::Alphanumeric => self.validate_alphanumeric(input),
            InputType::Text => self.validate_text(input),
            InputType::Html => self.sanitize_html(input),
        }
    }

    /// 验证邮箱格式
    fn validate_email(&self, email: &str) -> Result<String, SecurityError> {
        if email.len() > 254 {
            return Err(SecurityError::InvalidHeader {
                detail: "邮箱地址过长".to_string(),
            });
        }

        let email_regex =
            Regex::new(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$").map_err(|_| {
                SecurityError::InvalidHeader {
                    detail: "邮箱验证正则表达式错误".to_string(),
                }
            })?;

        if !email_regex.is_match(email) {
            return Err(SecurityError::InvalidHeader {
                detail: "邮箱格式无效".to_string(),
            });
        }

        Ok(email.to_string())
    }

    /// 验证URL格式
    fn validate_url(&self, url: &str) -> Result<String, SecurityError> {
        if url.len() > 2048 {
            return Err(SecurityError::InvalidHeader {
                detail: "URL过长".to_string(),
            });
        }

        match Url::parse(url) {
            Ok(parsed_url) => {
                // 检查协议
                if !["http", "https", "ftp", "ftps"].contains(&parsed_url.scheme()) {
                    return Err(SecurityError::InvalidHeader {
                        detail: "不支持的URL协议".to_string(),
                    });
                }
                Ok(url.to_string())
            }
            Err(_) => Err(SecurityError::InvalidHeader {
                detail: "URL格式无效".to_string(),
            }),
        }
    }

    /// 验证电话号码格式
    fn validate_phone(&self, phone: &str) -> Result<String, SecurityError> {
        let phone_regex =
            Regex::new(r"^[\+]?[1-9][\d]{0,15}$").map_err(|_| SecurityError::InvalidHeader {
                detail: "电话号码验证正则表达式错误".to_string(),
            })?;

        if !phone_regex.is_match(phone) {
            return Err(SecurityError::InvalidHeader {
                detail: "电话号码格式无效".to_string(),
            });
        }

        Ok(phone.to_string())
    }

    /// 验证用户名格式
    fn validate_username(&self, username: &str) -> Result<String, SecurityError> {
        if username.len() < 3 || username.len() > 20 {
            return Err(SecurityError::InvalidHeader {
                detail: "用户名长度必须在3-20个字符之间".to_string(),
            });
        }

        let username_regex =
            Regex::new(r"^[a-zA-Z0-9_-]+$").map_err(|_| SecurityError::InvalidHeader {
                detail: "用户名验证正则表达式错误".to_string(),
            })?;

        if !username_regex.is_match(username) {
            return Err(SecurityError::InvalidHeader {
                detail: "用户名只能包含字母、数字、下划线和连字符".to_string(),
            });
        }

        Ok(username.to_string())
    }

    /// 验证密码格式
    fn validate_password(&self, password: &str) -> Result<String, SecurityError> {
        if password.len() < 8 {
            return Err(SecurityError::InvalidHeader {
                detail: "密码长度至少8个字符".to_string(),
            });
        }

        if password.len() > 128 {
            return Err(SecurityError::InvalidHeader {
                detail: "密码长度不能超过128个字符".to_string(),
            });
        }

        // 检查是否包含常见弱密码
        let weak_passwords = vec![
            "password",
            "123456",
            "123456789",
            "qwerty",
            "abc123",
            "password123",
            "admin",
            "letmein",
            "welcome",
            "monkey",
        ];

        if weak_passwords.contains(&password.to_lowercase().as_str()) {
            return Err(SecurityError::InvalidHeader {
                detail: "密码过于简单，请使用更复杂的密码".to_string(),
            });
        }

        Ok(password.to_string())
    }

    /// 验证数字格式
    fn validate_numeric(&self, input: &str) -> Result<String, SecurityError> {
        let numeric_regex =
            Regex::new(r"^-?\d+(\.\d+)?$").map_err(|_| SecurityError::InvalidHeader {
                detail: "数字验证正则表达式错误".to_string(),
            })?;

        if !numeric_regex.is_match(input) {
            return Err(SecurityError::InvalidHeader {
                detail: "输入必须是有效的数字".to_string(),
            });
        }

        Ok(input.to_string())
    }

    /// 验证字母数字格式
    fn validate_alphanumeric(&self, input: &str) -> Result<String, SecurityError> {
        let alphanumeric_regex =
            Regex::new(r"^[a-zA-Z0-9]+$").map_err(|_| SecurityError::InvalidHeader {
                detail: "字母数字验证正则表达式错误".to_string(),
            })?;

        if !alphanumeric_regex.is_match(input) {
            return Err(SecurityError::InvalidHeader {
                detail: "输入只能包含字母和数字".to_string(),
            });
        }

        Ok(input.to_string())
    }

    /// 验证文本格式
    fn validate_text(&self, input: &str) -> Result<String, SecurityError> {
        if input.len() > 10000 {
            return Err(SecurityError::InvalidHeader {
                detail: "文本长度不能超过10000个字符".to_string(),
            });
        }

        // 移除危险字符
        let sanitized = input
            .chars()
            .filter(|c| !matches!(c, '\0' | '\r' | '\n' | '\t'))
            .collect::<String>();

        Ok(sanitized)
    }

    /// 清理HTML内容
    fn sanitize_html(&self, input: &str) -> Result<String, SecurityError> {
        // 移除所有HTML标签
        let html_regex = Regex::new(r"<[^>]*>").map_err(|_| SecurityError::InvalidHeader {
            detail: "HTML清理正则表达式错误".to_string(),
        })?;

        let sanitized = html_regex.replace_all(input, "");

        // 解码HTML实体
        let decoded = html_entity_decode(&sanitized);

        Ok(decoded)
    }

    /// 生成安全响应头
    pub fn generate_security_headers(&self, domain: Option<&str>) -> HashMap<String, String> {
        let mut headers = HashMap::new();

        // Content Security Policy
        let csp = if let Some(domain) = domain {
            format!(
                "default-src 'self' {}; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:; connect-src 'self' {}; frame-ancestors 'none'; base-uri 'self'; form-action 'self'",
                domain, domain
            )
        } else {
            "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'".to_string()
        };
        headers.insert("Content-Security-Policy".to_string(), csp);

        // X-Content-Type-Options
        headers.insert("X-Content-Type-Options".to_string(), "nosniff".to_string());

        // X-Frame-Options
        headers.insert("X-Frame-Options".to_string(), "DENY".to_string());

        // X-XSS-Protection
        headers.insert("X-XSS-Protection".to_string(), "1; mode=block".to_string());

        // Referrer-Policy
        headers.insert(
            "Referrer-Policy".to_string(),
            "strict-origin-when-cross-origin".to_string(),
        );

        // Permissions-Policy
        headers.insert(
            "Permissions-Policy".to_string(),
            "geolocation=(), microphone=(), camera=()".to_string(),
        );

        // Strict-Transport-Security (HSTS)
        headers.insert(
            "Strict-Transport-Security".to_string(),
            "max-age=31536000; includeSubDomains; preload".to_string(),
        );

        // Cross-Origin-Embedder-Policy
        headers.insert(
            "Cross-Origin-Embedder-Policy".to_string(),
            "require-corp".to_string(),
        );

        // Cross-Origin-Opener-Policy
        headers.insert(
            "Cross-Origin-Opener-Policy".to_string(),
            "same-origin".to_string(),
        );

        // Cross-Origin-Resource-Policy
        headers.insert(
            "Cross-Origin-Resource-Policy".to_string(),
            "same-origin".to_string(),
        );

        // Cache-Control (for sensitive pages)
        headers.insert(
            "Cache-Control".to_string(),
            "no-store, no-cache, must-revalidate, proxy-revalidate".to_string(),
        );

        // Pragma
        headers.insert("Pragma".to_string(), "no-cache".to_string());

        // Expires
        headers.insert("Expires".to_string(), "0".to_string());

        headers
    }

    /// 生成CSRF Token
    pub fn generate_csrf_token(&mut self, session_id: &str) -> String {
        let current_time = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let token = format!("{}:{}", session_id, current_time);
        let token_hash = self.hash_sha256(&token);

        self.csrf_tokens.insert(token_hash.clone(), current_time);
        token_hash
    }

    /// 验证CSRF Token
    pub fn verify_csrf_token(&self, token: &str, session_id: &str) -> bool {
        if let Some(&timestamp) = self.csrf_tokens.get(token) {
            let current_time = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs();

            // Token有效期1小时
            if current_time - timestamp < 3600 {
                let expected_token = format!("{}:{}", session_id, timestamp);
                let expected_hash = self.hash_sha256(&expected_token);
                return expected_hash == token;
            }
        }
        false
    }

    /// 增强的CSRF保护检查
    pub fn enhanced_csrf_check(&self, request: &HttpRequestInfo) -> Vec<SecurityViolation> {
        let mut violations = Vec::new();

        // 对于GET请求通常不需要CSRF检查
        if request.method.to_uppercase() == "GET" {
            return violations;
        }

        // 检查Origin头
        if let Some(origin) = request.headers.get("origin") {
            if let Ok(origin_url) = Url::parse(origin) {
                if let Ok(request_url) = Url::parse(&request.url) {
                    if origin_url.host() != request_url.host() {
                        violations.push(SecurityViolation {
                            rule_type: SecurityRuleType::CsrfProtection,
                            severity: SecuritySeverity::High,
                            message: "Origin域名与请求域名不匹配".to_string(),
                            field: Some("origin".to_string()),
                            value: Some(origin.clone()),
                        });
                    }
                }
            }
        }

        // 检查Referer头
        if let Some(referer) = &request.referer {
            if let Ok(referer_url) = Url::parse(referer) {
                if let Ok(request_url) = Url::parse(&request.url) {
                    if referer_url.host() != request_url.host() {
                        violations.push(SecurityViolation {
                            rule_type: SecurityRuleType::CsrfProtection,
                            severity: SecuritySeverity::Medium,
                            message: "Referer域名与请求域名不匹配".to_string(),
                            field: Some("referer".to_string()),
                            value: Some(referer.clone()),
                        });
                    }
                }
            }
        }

        // 检查CSRF token
        let token = request
            .form_data
            .get(&self.config.csrf_token_name)
            .or_else(|| request.headers.get(&self.config.csrf_token_name))
            .or_else(|| request.headers.get("x-csrf-token"));

        if token.is_none() {
            violations.push(SecurityViolation {
                rule_type: SecurityRuleType::CsrfProtection,
                severity: SecuritySeverity::High,
                message: "缺少CSRF保护token".to_string(),
                field: Some("csrf_token".to_string()),
                value: None,
            });
        }

        // 检查SameSite Cookie
        if let Some(cookie) = request.headers.get("cookie") {
            if !cookie.contains("SameSite=Strict") && !cookie.contains("SameSite=Lax") {
                violations.push(SecurityViolation {
                    rule_type: SecurityRuleType::CsrfProtection,
                    severity: SecuritySeverity::Low,
                    message: "建议使用SameSite Cookie属性".to_string(),
                    field: Some("cookie".to_string()),
                    value: Some("SameSite属性缺失".to_string()),
                });
            }
        }

        violations
    }

    /// 生成双重提交CSRF Token
    pub fn generate_double_submit_csrf_token(&mut self, session_id: &str) -> (String, String) {
        let current_time = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let token_data = format!(
            "{}:{}:{}",
            session_id,
            current_time,
            self.generate_random_password(16)
        );
        let token_hash = self.hash_sha256(&token_data);

        self.csrf_tokens.insert(token_hash.clone(), current_time);

        // 返回token和cookie值
        (token_hash.clone(), token_hash)
    }

    /// 验证双重提交CSRF Token
    pub fn verify_double_submit_csrf_token(&self, form_token: &str, cookie_token: &str) -> bool {
        if form_token != cookie_token {
            return false;
        }

        if let Some(&timestamp) = self.csrf_tokens.get(form_token) {
            let current_time = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs();

            // Token有效期1小时
            return current_time - timestamp < 3600;
        }

        false
    }
}

// ================== 加密解密模块 ==================

impl SecurityGuard {
    /// SHA256哈希
    pub fn hash_sha256(&self, data: &str) -> String {
        let mut hasher = Sha256::default();
        hasher.update(data.as_bytes());
        format!("{:x}", hasher.finalize())
    }

    /// HMAC-SHA256签名
    pub fn hmac_sha256(&self, key: &str, data: &str) -> Result<String, SecurityError> {
        type HmacSha256 = Hmac<Sha256>;

        let mut mac = <HmacSha256 as Mac>::new_from_slice(key.as_bytes()).map_err(|e| {
            SecurityError::CryptoError {
                detail: format!("HMAC key error: {}", e),
            }
        })?;

        mac.update(data.as_bytes());
        let result = mac.finalize();
        Ok(format!("{:x}", result.into_bytes()))
    }

    /// AES-256-GCM加密
    pub fn encrypt_aes256(&self, key: &str, plaintext: &str) -> Result<String, SecurityError> {
        // 使用SHA256将key扩展到32字节
        let key_hash = self.hash_sha256(key);
        let key_bytes = hex::decode(&key_hash).map_err(|e| SecurityError::CryptoError {
            detail: format!("Key decode error: {}", e),
        })?;

        let key = Key::<Aes256Gcm>::from_slice(&key_bytes);
        let cipher = Aes256Gcm::new(key);

        // 生成随机nonce
        let mut nonce_bytes = [0u8; 12];
        thread_rng().fill(&mut nonce_bytes);
        let nonce = Nonce::from_slice(&nonce_bytes);

        let ciphertext = cipher.encrypt(nonce, plaintext.as_bytes()).map_err(|e| {
            SecurityError::CryptoError {
                detail: format!("Encryption error: {}", e),
            }
        })?;

        // 将nonce和ciphertext组合并base64编码
        let mut result = nonce_bytes.to_vec();
        result.extend_from_slice(&ciphertext);
        Ok(general_purpose::STANDARD.encode(result))
    }

    /// AES-256-GCM解密
    pub fn decrypt_aes256(&self, key: &str, encrypted_data: &str) -> Result<String, SecurityError> {
        let key_hash = self.hash_sha256(key);
        let key_bytes = hex::decode(&key_hash).map_err(|e| SecurityError::CryptoError {
            detail: format!("Key decode error: {}", e),
        })?;

        let key = Key::<Aes256Gcm>::from_slice(&key_bytes);
        let cipher = Aes256Gcm::new(key);

        // 解码base64数据
        let data = general_purpose::STANDARD
            .decode(encrypted_data)
            .map_err(|e| SecurityError::CryptoError {
                detail: format!("Base64 decode error: {}", e),
            })?;

        if data.len() < 12 {
            return Err(SecurityError::CryptoError {
                detail: "Invalid encrypted data length".to_string(),
            });
        }

        // 提取nonce和ciphertext
        let nonce = Nonce::from_slice(&data[..12]);
        let ciphertext = &data[12..];

        let plaintext =
            cipher
                .decrypt(nonce, ciphertext)
                .map_err(|e| SecurityError::CryptoError {
                    detail: format!("Decryption error: {}", e),
                })?;

        String::from_utf8(plaintext).map_err(|e| SecurityError::CryptoError {
            detail: format!("UTF-8 decode error: {}", e),
        })
    }

    /// 生成随机密码
    pub fn generate_random_password(&self, length: usize) -> String {
        const CHARSET: &[u8] =
            b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";
        let mut rng = thread_rng();

        (0..length)
            .map(|_| {
                let idx = rng.gen_range(0..CHARSET.len());
                CHARSET[idx] as char
            })
            .collect()
    }

    /// 密码强度检查
    pub fn check_password_strength(&self, password: &str) -> PasswordStrength {
        let mut score = 0;
        let mut issues = Vec::new();

        if password.len() >= 8 {
            score += 1;
        } else {
            issues.push("密码长度至少8位".to_string());
        }

        if password.chars().any(|c| c.is_lowercase()) {
            score += 1;
        } else {
            issues.push("需要包含小写字母".to_string());
        }

        if password.chars().any(|c| c.is_uppercase()) {
            score += 1;
        } else {
            issues.push("需要包含大写字母".to_string());
        }

        if password.chars().any(|c| c.is_numeric()) {
            score += 1;
        } else {
            issues.push("需要包含数字".to_string());
        }

        if password
            .chars()
            .any(|c| "!@#$%^&*()_+-=[]{}|;:,.<>?".contains(c))
        {
            score += 1;
        } else {
            issues.push("需要包含特殊字符".to_string());
        }

        let strength = match score {
            0..=1 => PasswordStrengthLevel::Weak,
            2..=3 => PasswordStrengthLevel::Medium,
            4 => PasswordStrengthLevel::Strong,
            _ => PasswordStrengthLevel::VeryStrong,
        };

        PasswordStrength {
            level: strength,
            score,
            issues,
        }
    }
}

// ================== 密码强度结构 ==================

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PasswordStrength {
    pub level: PasswordStrengthLevel,
    pub score: u8,
    pub issues: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PasswordStrengthLevel {
    Weak,
    Medium,
    Strong,
    VeryStrong,
}

// ================== 输入类型定义 ==================

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum InputType {
    Email,
    Url,
    Phone,
    Username,
    Password,
    Numeric,
    Alphanumeric,
    Text,
    Html,
}

// ================== 测试模块 ==================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_path_traversal_detection() {
        let mut guard = SecurityGuard::new_with_default();
        let mut request = create_test_request();
        request.url = "http://example.com/files?path=../../../etc/passwd".to_string();

        let result = guard.check_request(&request);
        assert!(!result.is_safe);
        assert!(
            result
                .violations
                .iter()
                .any(|v| matches!(v.rule_type, SecurityRuleType::PathTraversal))
        );
    }

    #[test]
    fn test_xss_detection() {
        let mut guard = SecurityGuard::new_with_default();
        let mut request = create_test_request();
        request.form_data.insert(
            "comment".to_string(),
            "<script>alert('xss')</script>".to_string(),
        );

        let result = guard.check_request(&request);
        assert!(!result.is_safe);
        assert!(
            result
                .violations
                .iter()
                .any(|v| matches!(v.rule_type, SecurityRuleType::XssInjection))
        );
    }

    #[test]
    fn test_sql_injection_detection() {
        let mut guard = SecurityGuard::new_with_default();
        let mut request = create_test_request();
        request
            .query_params
            .insert("id".to_string(), "1 OR 1=1--".to_string());

        let result = guard.check_request(&request);
        assert!(!result.is_safe);
        assert!(
            result
                .violations
                .iter()
                .any(|v| matches!(v.rule_type, SecurityRuleType::SqlInjection))
        );
    }

    #[test]
    fn test_encryption_decryption() {
        let guard = SecurityGuard::new_with_default();
        let key = "my_secret_key";
        let plaintext = "Hello, World!";

        let encrypted = guard.encrypt_aes256(key, plaintext).unwrap();
        let decrypted = guard.decrypt_aes256(key, &encrypted).unwrap();

        assert_eq!(plaintext, decrypted);
    }

    #[test]
    fn test_password_strength() {
        let guard = SecurityGuard::new_with_default();

        let weak = guard.check_password_strength("123");
        assert!(matches!(weak.level, PasswordStrengthLevel::Weak));

        let strong = guard.check_password_strength("MyStr0ng!Pass");
        assert!(matches!(strong.level, PasswordStrengthLevel::Strong));
    }

    fn create_test_request() -> HttpRequestInfo {
        HttpRequestInfo {
            method: "GET".to_string(),
            url: "http://example.com/test".to_string(),
            headers: HashMap::new(),
            body: None,
            query_params: HashMap::new(),
            form_data: HashMap::new(),
            cookies: HashMap::new(),
            client_ip: "127.0.0.1".to_string(),
            user_agent: Some("Mozilla/5.0 Test".to_string()),
            referer: Some("http://example.com".to_string()),
        }
    }
}

// 补充hex包的简单实现
mod hex {
    pub fn decode(s: &str) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
        if s.len() % 2 != 0 {
            return Err("Invalid hex string length".into());
        }

        let mut result = Vec::new();
        for i in (0..s.len()).step_by(2) {
            let byte_str = &s[i..i + 2];
            let byte = u8::from_str_radix(byte_str, 16)?;
            result.push(byte);
        }
        Ok(result)
    }
}

// HTML实体解码函数
fn html_entity_decode(input: &str) -> String {
    let mut result = input.to_string();

    // 常见的HTML实体
    let entities = vec![
        ("&amp;", "&"),
        ("&lt;", "<"),
        ("&gt;", ">"),
        ("&quot;", "\""),
        ("&#39;", "'"),
        ("&nbsp;", " "),
        ("&copy;", "©"),
        ("&reg;", "®"),
        ("&trade;", "™"),
        ("&euro;", "€"),
        ("&pound;", "£"),
        ("&yen;", "¥"),
        ("&cent;", "¢"),
        ("&sect;", "§"),
        ("&para;", "¶"),
        ("&middot;", "·"),
        ("&hellip;", "…"),
        ("&ndash;", "–"),
        ("&mdash;", "—"),
        ("&lsquo;", "'"),
        ("&rsquo;", "'"),
        ("&ldquo;", "\""),
        ("&rdquo;", "\""),
        ("&bull;", "•"),
        ("&deg;", "°"),
        ("&plusmn;", "±"),
        ("&times;", "×"),
        ("&divide;", "÷"),
        ("&frac14;", "¼"),
        ("&frac12;", "½"),
        ("&frac34;", "¾"),
        ("&sup1;", "¹"),
        ("&sup2;", "²"),
        ("&sup3;", "³"),
        ("&alpha;", "α"),
        ("&beta;", "β"),
        ("&gamma;", "γ"),
        ("&delta;", "δ"),
        ("&epsilon;", "ε"),
        ("&zeta;", "ζ"),
        ("&eta;", "η"),
        ("&theta;", "θ"),
        ("&iota;", "ι"),
        ("&kappa;", "κ"),
        ("&lambda;", "λ"),
        ("&mu;", "μ"),
        ("&nu;", "ν"),
        ("&xi;", "ξ"),
        ("&omicron;", "ο"),
        ("&pi;", "π"),
        ("&rho;", "ρ"),
        ("&sigma;", "σ"),
        ("&tau;", "τ"),
        ("&upsilon;", "υ"),
        ("&phi;", "φ"),
        ("&chi;", "χ"),
        ("&psi;", "ψ"),
        ("&omega;", "ω"),
    ];

    for (entity, replacement) in entities {
        result = result.replace(entity, replacement);
    }

    // 处理数字实体 &#123; 和 &#x1A;
    let mut i = 0;
    while i < result.len() {
        if result[i..].starts_with("&#") {
            let end = result[i..].find(';');
            if let Some(end_pos) = end {
                let entity = &result[i..i + end_pos + 1];
                if entity.starts_with("&#x") {
                    // 十六进制实体
                    let hex_str = &entity[3..entity.len() - 1];
                    if let Ok(code) = u32::from_str_radix(hex_str, 16) {
                        if let Some(ch) = std::char::from_u32(code) {
                            result = result.replace(entity, &ch.to_string());
                        }
                    }
                } else {
                    // 十进制实体
                    let dec_str = &entity[2..entity.len() - 1];
                    if let Ok(code) = dec_str.parse::<u32>() {
                        if let Some(ch) = std::char::from_u32(code) {
                            result = result.replace(entity, &ch.to_string());
                        }
                    }
                }
            }
        }
        i += 1;
    }

    result
}
